package com.chatplus.application.aiprocessor.function.impl;

import com.chatplus.application.aiprocessor.function.TriggerFunctionService;
import com.chatplus.application.aiprocessor.provider.TriggerFunctionServiceProvider;
import com.chatplus.application.common.domain.response.TurnRightResponse;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ImgResultDto;
import com.chatplus.application.domain.entity.functions.FunctionEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * dalle3画图
 */
@Service(value = TriggerFunctionServiceProvider.SERVICE_NAME_PRE + Dalle3ServiceImpl.DALLE3)
public class Dalle3ServiceImpl extends TriggerFunctionService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(Dalle3ServiceImpl.class);

    public static final String DALLE3 = "dalle3";
    private final ObjectMapper objectMapper;

    public Dalle3ServiceImpl(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String executeReturnMarkdown(FunctionEntity functionEntity, String arguments) {
        String result = "";
        try {
            result = commonExecute(functionEntity, arguments);
            LOGGER.message("dalle3画图结果").context("result", result).info();
            TurnRightResponse turnRightResponse = objectMapper.readValue(result, TurnRightResponse.class);
            if (Objects.equals(turnRightResponse.getCode(), TurnRightResponse.SUCCESS)
                    && Objects.nonNull(turnRightResponse.getData())) {
                ImgResultDto imgResultDto =
                        objectMapper.readValue(objectMapper.writeValueAsString(turnRightResponse.getData()), ImgResultDto.class);
                return String.format("下面是根据您的描述创作的图片，它描绘了 【%s】 的场景。 %n%n![](%s)%n", imgResultDto.getRevisedPrompt(), imgResultDto.getUrl());
            }
        } catch (Exception e) {
            LOGGER.message("dalle3画图结果报错").context("result", result).exception(e).error();
        }
        return "dalle3画图结果异常，等待管理员处理";
    }

    @Override
    public String getFunctionChannel() {
        return DALLE3;
    }
}
